﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Threading;
using System.Windows;
using System.Windows.Input;
using SalesPoint.Commands;
using SalesPoint.Model;
using SalesPoint.Security;
using Xtensive.Orm;
using Xtensive.Orm.Security;

namespace SalesPoint.ViewModels
{
  public class OrderListViewModel : GenericListViewModel<Order>
  {
    private DelegateCommand approveItemCommand;

    public ICommand ApproveItemCommand
    {
      get {
        if (approveItemCommand != null)
          return approveItemCommand;

        approveItemCommand = new DelegateCommand(ApproveItem, CanApproveItem);
        return approveItemCommand;
      }
    }

    private bool CanApproveItem()
    {
      var securityContext = Session.GetImpersonationContext();
      if (securityContext == null)
        return false;
      return securityContext.Permissions.Contains<OrderPermission>(p => p.CanApprove);
    }

    private void ApproveItem()
    {
      var e = Session.GetImpersonationContext().Principal as Employee;
      string message =
        string.Format(
          "You logged in as {0} {1}, {2}, {3}.\nThis MessageBox demonstrates that you have permission to approve Order.",
          e.FirstName, e.LastName, e.Title, e.Address.City);
      MessageBox.Show(message, "Sorry, this is temporary stub", MessageBoxButton.OK, MessageBoxImage.Information);
    }

    protected override Order CreateItem()
    {
      return new Order(Session);
    }

    protected override Window GetItemView()
    {
      throw new NotImplementedException();
    }

    protected override ObservableCollection<Order> GetItems()
    {
      var query = Session.Query.All<Order>()
        .Prefetch(p => p.Employee)
        .Prefetch(p => p.ShipVia)
        .Prefetch(p => p.Customer);

      return new ObservableCollection<Order>(query);
    }

    public OrderListViewModel(Session session)
      : base(session, "Orders")
    {}
  }
}